
const osubmit = document.getElementById("btn");
const otel = document.getElementById("tel");
const opassword = document.getElementById("pw");


function ajax(url, callback, data){
    let str = "";
    for(let i in data){
        str += `${i}=${data[i]}&`
    }
    url += "?" + str;
    const xhr = new XMLHttpRequest();
    xhr.open("get",url)
    xhr.onload = function(){
        if(xhr.status === 200){
            callback(xhr.responseText)
        }
    }
    xhr.send();
}
let opw2 = document.getElementById("pww")
let tel=false,pw=false,pw2=false;
otel.onblur = function(){
    var span = this.nextElementSibling;
    console.log(this.nextElementSibling)
    if(/^1[3-9]\d{9}$/.test(this.value)){
        span.innerHTML = "√";
        tel = true;
    }else{
        span.innerHTML = "请输入正确的手机号";
        tel = false;
    }
}
opassword.onblur = function(){
    var span = this.nextElementSibling;
    var a = /\d/.test(this.value) ? 1 : 0;
    var b = /[a-z]/i.test(this.value) ? 1 : 0;
    var c = /[^a-z\d]/i.test(this.value) ? 1 : 0;
    switch(a+b+c){
        case 1:span.innerHTML = "密码强度：弱";break;
        case 2:span.innerHTML = "密码强度：中";break;
        case 3:span.innerHTML = "密码强度：强";break;
    }
    pw = true;
    if(opw2.value === "") return;
    if(this.value === opw2.value){
        opw2.nextElementSibling.innerHTML = "√"
        pw2 = true;
    }else{
        opw2.nextElementSibling.innerHTML = "两次密码须一致"
        pw2 = false;
    }
}
opw2.onblur = function(){
    var span = this.nextElementSibling;
    if(this.value === opassword.value){
        span.innerHTML = "一致"
        pw2 = true;
    }else{
        span.innerHTML = "不一致"
        pw2 = false;
    }
}
osubmit.onclick = function(){
    ajax("http://localhost:3000/api",function(res){
        res = JSON.parse(res);
        if(res.code === 0){
            alert(res.title);
            otel.value = "";
            otel.focus();
        }else if(res.code === 1  && pw && pw2 && tel){
            if(confirm("注册成功，立刻去登录?")){
                location.href = "../login.html";
            }
        }
    },{
        type:"register",
        username:otel.value,
        password:opassword.value
    })
}
const ok = document.querySelector(".ok")
const alert = document.querySelector(".alert-box-mask")
ok.onclick=function(){
    alert.style.display="none"
}